/*
 * Copyright (c) 2010 Mathias Garbe <code@mathias-garbe.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "GameInfo.hpp"

GameInfo::GameInfo(Games::GameType game, std::string reg32, std::string reg64)
{
    this->game = game;
    this->reg32 = reg32;
    this->reg64 = reg64;
}

std::string GameInfo::getExe()
{
    //ClientConfig *config = ClientConfig::Instance();
    QSettings settings;
    if(this->game == Games::NOGAME)
    {
        throw std::runtime_error("Game not set");
    }

    std::string path = "";

    HKEY hKey32, hKey64;
	DWORD bufferSize = 1024 * 10;
    char* tmp = (char*) malloc( bufferSize );


    // check for custom path
    //
    std::string gameSetting = "CustomPath/";
    gameSetting.append(Games::getGameString(this->game));
    std::string customPath = settings.value(gameSetting.c_str(), "").toString().toStdString(); //config->getCustomPath(this->game);
    customPath.append("\\");
    customPath.append(Games::getGameExeName(this->game));
    if(FileExists(customPath.c_str()))
    {
        path = customPath;
    }

    // try 32 bit registry
    if(path == "" && RegOpenKeyA(HKEY_LOCAL_MACHINE, (LPCSTR)reg32.c_str(), &hKey32) == ERROR_SUCCESS)
    {
        if(RegQueryValueExA(hKey32, "InstallPath", NULL, NULL, (unsigned char*)tmp, &bufferSize) == ERROR_SUCCESS)
        {
            if(FileExists(tmp))
            {
                path = tmp;
            }
        }
        RegCloseKey(hKey32);
    }

    // try for 64 bit
    if(path == "" && RegOpenKeyA(HKEY_LOCAL_MACHINE, (LPCSTR)reg64.c_str(), &hKey64) == ERROR_SUCCESS)
    {
        if(RegQueryValueExA(hKey64, "InstallPath", NULL, NULL, (unsigned char*)tmp, &bufferSize) == ERROR_SUCCESS)
        {
            if(FileExists(tmp))
            {
                path = tmp;
            }
        }
        RegCloseKey(hKey64);
    }

	free(tmp);
    return path;
}

std::string GameInfo::getPath()
{
    std::string gameExe = this->getExe();
    if(gameExe.find_last_of("\\") != std::string::npos)
    {
        return gameExe.substr(0, gameExe.find_last_of("\\") + 1);
    }
    return "";
}


Games::GameType GameInfo::getType()
{
    return this->game;
}
